<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
			<el-form-item label="患者姓名" prop="patientName">
				<el-input
					v-model="queryParams.patientName"
					placeholder="请输入患者姓名"
					clearable
					size="small"
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="手机号" prop="phone">
				<el-input
					v-model="queryParams.phone"
					placeholder="请输入手机号"
					clearable
					size="small"
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="性别" prop="sex">
				<el-select v-model="queryParams.sex" placeholder="请选择性别" clearable size="small">
					<el-option v-for="dict in sexOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button
					type="primary"
					icon="el-icon-plus"
					size="mini"
					@click="handleAdd"
					:disabled="true"
				>新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="success"
					icon="el-icon-edit"
					size="mini"
					:disabled="single"
					@click="handleUpdate"
				>修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="danger"
					icon="el-icon-delete"
					size="mini"
					:disabled="multiple"
					@click="handleDelete"
				>删除</el-button>
			</el-col>
<!--			<el-col :span="1.5">
				<el-popconfirm
					confirm-button-text='当前页'
					cancel-button-text='全部'
					icon="el-icon-info"
					title="请选择导出内容"
					cancel-button-type="default"
					@confirm="handleExport(false)"
					@cancel="handleExport(true)"
				>
					<el-button
						type="warning"
						icon="el-icon-download"
						size="mini"
						:loading="exporting"
						slot="reference"
					>导出</el-button>
				</el-popconfirm>
			</el-col>-->
			<el-col :span="1.5">
				<el-dropdown size="mini" split-button type="warning" @command="handleExportCommand">
					<i class="el-icon-download"></i> &nbsp;&nbsp;导出
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item command="all">导出全部</el-dropdown-item>
						<el-dropdown-item command="curr">导出当前页</el-dropdown-item>
						<el-dropdown-item command="month">按月份导出</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="patientList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column type="index" label="序号" width="55" align="center" :index="indexMethod" />
			<el-table-column label="患者姓名" align="center" prop="patientName" />
			<el-table-column label="手机号" align="center" prop="phone" />
			<el-table-column label="性别" align="center" prop="sex" >
				<template slot-scope="scope">
					{{ labelFilter(scope.row.sex, sexOptions) }}
				</template>
			</el-table-column>
			<el-table-column label="出生年月" align="center" prop="birthDate" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.birthDate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
      <el-table-column label="积分" align="center">
        <template slot-scope="scope">{{scope.row.point}}</template>
      </el-table-column>
      <el-table-column label="场景值" align="center">
        <template slot-scope="scope">{{scope.row.scene}}</template>
      </el-table-column>
			<el-table-column label="扫入二维码的医生" align="center">
				<template slot-scope="scope">{{scope.row.qrDoctor}}</template>
			</el-table-column>
			<el-table-column label="省份" align="center">
				<template slot-scope="scope">{{scope.row.user ? scope.row.user.province: ''}}</template>
			</el-table-column>
			<el-table-column label="城市" align="center">
				<template slot-scope="scope">{{scope.row.user ? scope.row.user.city: ''}}</template>
			</el-table-column>
			<el-table-column label="区县" align="center">
				<template slot-scope="scope">{{scope.row.user ? scope.row.user.area: ''}}</template>
			</el-table-column>
			<el-table-column label="注册时间" align="center">
				<template slot-scope="scope">{{parseTime(scope.row.createTime, '{y}-{m}-{d}')}}</template>
			</el-table-column>
			<el-table-column label="操作" align="center">
				<template slot-scope="scope">
					<el-dropdown>
						<span class="el-dropdown-link">
							操作<i class="el-icon-arrow-down el-icon--right"></i>
						</span>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item @click.native="handleUpdate(scope.row)" disabled>修改</el-dropdown-item>
							<el-dropdown-item @click.native="handleDelete(scope.row)" disabled>删除</el-dropdown-item>
							<el-dropdown-item @click.native="testHistory(scope.row)">自测记录</el-dropdown-item>
							<el-dropdown-item @click.native="bindDoctor(scope.row)">绑定医生</el-dropdown-item>
              <el-dropdown-item @click.native="updatePoint(scope.row)">积分修改</el-dropdown-item>
<!--							<el-dropdown-item @click.native="sendSubscribe(scope.row.userId)">发送消息</el-dropdown-item>-->
						</el-dropdown-menu>
					</el-dropdown>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total>0"
			:total="total"
			:page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize"
			@pagination="getList"
		/>

		<!-- 添加或修改患者对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="患者姓名" prop="patientName">
					<el-input v-model="form.patientName" placeholder="请输入患者姓名" />
				</el-form-item>
				<el-form-item label="手机号" prop="phone">
					<el-input v-model="form.phone" placeholder="请输入手机号" />
				</el-form-item>
				<el-form-item label="性别" prop="sex">
					<el-select v-model="form.sex" placeholder="请选择性别">
						<el-option v-for="dict in sexOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="出生年月" prop="birthDate">
					<el-date-picker clearable size="small" style="width: 200px"
									v-model="form.birthDate"
									type="date"
									value-format="yyyy-MM-dd"
									placeholder="选择出生年月">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="省份" prop="province">
					<el-input v-model="form.province" placeholder="请输入省份" />
				</el-form-item>
				<el-form-item label="城市" prop="city">
					<el-input v-model="form.city" placeholder="请输入城市" />
				</el-form-item>
				<el-form-item label="区域" prop="area">
					<el-input v-model="form.area" placeholder="请输入区域" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<subscribe-dialog v-if="dialogFlag" :currentUserId="currentUserId" :type="type" @close="subscribeClose"></subscribe-dialog>
		<export-month-dialog v-if="exportMonth.visible" :visible.sync="exportMonth.visible" bus-type="patient"></export-month-dialog>
	</div>
</template>

<script>
import { listPatient, getPatient, delPatient, addPatient, updatePatient, exportPatient } from "@/api/patient";
import SubscribeDialog from "./component/subscribe-dialog";
import ExportMonthDialog from '@/views/components/export-month-dialog';

export default {
	name: "Patient",
	components: { SubscribeDialog, ExportMonthDialog },
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 患者表格数据
			patientList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				userId: null,
				bindId: null,
				patientName: null,
				phone: null,
				sex: null,
				birthDate: null,
				province: null,
				city: null,
				area: null,
				headUrl: null,
				isDelete: null,
				bindTime: null,
				idCard: null,
				medicalCard: null,
				idType: null,
				visitCard: null,
				address: null,
				relation: null,
				isDefault: null,
				orderByColumn: 'patient_id',
				isAsc: 'desc'
			},
			rules: {
				patientName: [{
					required: true,
					message: '请输入患者姓名',
					trigger: 'blur'
				}],
				phone: [{
					required: true,
					message: '请输入手机号',
					trigger: 'blur'
				}],
				sex: [{
					required: true,
					message: '请选择性别',
					trigger: 'change'
				}],
				birthDate: [{
					required: true,
					message: '请选择出生日期',
					trigger: 'change'
				}],
			},
			// 表单参数
			form: {},
			sexOptions: [],
			dialogFlag: false,
			currentUserId: undefined,
			type: 'patient',
			exporting: false,
			exportMonth: {
				visible: false
			}
		};
	},
	created() {
		this.getList();
		this.getDicts("sys_user_sex").then((response) => {
			this.sexOptions = response.data;
		});
	},
	computed: {
		labelFilter() {
			return ((text, option) => {
				for (let i = 0; i < option.length; i++) {
					if (option[i].dictValue == text) {
						return option[i].dictLabel;
					}
				}
			})
		}
	},
	methods: {
		testHistory(row) {
			this.$router.push({path: '/testHistory/testHistory', query: { userId: row.userId }})
		},
		bindDoctor(row) {
			if (!row.bindId) {
				this.$message.info('该患者暂无绑定医生');
			} else {
				this.$router.push({path: '/doctor/view', query: {doctorId: row.bindId}})
			}
		},
    updatePoint(row) {
      this.$prompt('请输入积分', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(0|[1-9][0-9]*)$/,
        inputErrorMessage: '积分请输入整数'
      }).then(({ value }) => {
        updatePatient({patientId: row.patientId, point: value}).then(res => {
          if (res.code === 200) {
            this.msgSuccess("修改成功");
            this.getList();
          }
        })
      });
    },
		/** 查询患者列表 */
		getList() {
			this.loading = true;
			listPatient(this.queryParams).then(response => {
				this.patientList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				patientId: null,
				userId: null,
				bindId: null,
				patientName: null,
				phone: null,
				sex: null,
				birthDate: null,
				province: null,
				city: null,
				area: null,
				provinceId: null,
				cityId: null,
				areaId: null,
				headUrl: null,
				isDelete: null,
				bindTime: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
				idCard: null,
				medicalCard: null,
				idType: null,
				visitCard: null,
				address: null,
				relation: null,
				isDefault: null
			};
			this.resetForm("form");
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.patientId)
			this.single = selection.length!==1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = "添加患者";
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const patientId = row.patientId || this.ids
			getPatient(patientId).then(response => {
				this.form = response.data;
				this.open = true;
				this.title = "修改患者";
			});
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					if (this.form.patientId != null) {
						updatePatient(this.form).then(response => {
							if (response.code === 200) {
								this.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							}
						});
					} else {
						addPatient(this.form).then(response => {
							if (response.code === 200) {
								this.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							}
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const patientIds = row.patientId || this.ids;
			this.$confirm('是否确认删除患者编号为"' + patientIds + '"的数据项?', "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(function() {
				return delPatient(patientIds);
			}).then(() => {
				this.getList();
				this.msgSuccess("删除成功");
			}).catch(function() {});
		},
		/** 导出按钮操作 */
		handleExport(flag) {
			const queryParams = this.queryParams;
			this.$confirm('是否确认导出所有患者数据项?', "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(() => {
				this.exporting = true;
				this.msgInfo('当前患者数量较多，可能导出耗时较长，请您耐心等待...')
				if(flag) {
					return exportPatient();
				} else {
					return exportPatient(queryParams);
				}
			}).then(response => {
				this.exporting = false;
				this.download(response.msg);
			}).catch(function() {});
		},
		handleExportCommand(command) {
			console.log(command)
			if (command === 'all') {
				this.handleExport(true);
			} else if (command === 'curr') {
				this.handleExport(false);
			} else if (command === 'month') {
				this.exportMonth.visible = true;
			}
		},
		subscribeClose() {
			this.dialogFlag = false;
		},
		sendSubscribe(userId) {
			this.dialogFlag = true;
			this.currentUserId = userId;
		},
		indexMethod(index) {
			return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
		}
	}
};
</script>
<style lang="scss" scoped>
.el-dropdown-link {
	cursor: pointer;
	color: #409EFF;
}
.el-icon-arrow-down {
	font-size: 12px;
}
</style>
